#    Supsta
#    Copyright (c) 2014 Sebastian Dufner
#
#    This file is part of Supsta.
#
#    Supsta is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Supsta is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

require 'supsta/project/texture_provider'

module Supsta

  ##
  #

  class Filter

    ##
    # Returns a Filter, restoring it from +hash+.

    def self.unhash(hash)
      return unless hash

      layer = new(hash[:name], hash[:renderer])
      unhash(hash[:child]).insert_below layer if hash[:child]
      layer.mtime, layer.last_compiled = hash[:mtime], hash[:last_compiled]

      layer
    end

    def initialize(name, mtime = Time.now, renderer)
      @name, @renderer, @mtime = name, renderer, mtime
    end

    attr_accessor :renderer
    attr_reader :parent

    ##
    # Deletes this Filter from the stack.

    def delete
      child.parent = parent if child
      parent.child = child
      parent, child = nil

      self
    end

    ##
    # Insert this Filter below +layer+.

    def insert_below(layer)
      delete if parent
      parent, child = layer, layer.child
      child.parent = self if child
      parent.child = self
    end

    ##
    # Returns a Hash representing this Filter.
    #
    # <b>See also:</b> ::unhash

    def to_hash
      super.merge!(renderer: renderer.to_hash)
    end

  protected

    ##
    # Makes +new_parent+ this Filter's #parent, updating #mtime in the process.

    def parent=(new_parent)
      mtime = Time.now
      @parent = new_parent
    end

  end
end



